﻿using AiXiu.IService;
using AiXiu.Model;
using AiXiu.Service;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AiXiu.WebSite.Controllers
{
    [Authorize]
    public class FriendsController : Controller
    {
        public ActionResult Index()
        {
            // 获取好友列表
            int userId = IdentityManager.ReadUser().Id;
            IFriendService friendService = new FriendService();
            Dictionary<int, Friend> friendDictionary = friendService.GetFriends(userId);
            return View(friendDictionary);
        }

        [HttpPost]
        public ActionResult AddFriend(int userId)
        {
            // 添加好友
            IFriendService friendService = new FriendService();
            int selfId = IdentityManager.ReadUser().Id;
            bool friendResult = friendService.AddFriend(selfId, userId);
            if (!friendResult)
            {
                // 提示添加失败
                return Json(OperResult.Failed("添加失败！"));
            }
            else
            {
                // 提示并跳转页面
                return Json(OperResult.Succeed());
            }
        }

        public ActionResult Chat(int to)
        {
            TBUsers user = IdentityManager.ReadUser();
            IFriendService friendService = new FriendService();
            Friend friend= friendService.GetFriend(user.Id, to);
            ViewBag.user = user;
            ViewBag.to = to;
            return View(friend);
        }

        public ActionResult ChatRecord(int selfId,int to,int pageNumber,int pageSize)
        {
            // 读取列表
            IFriendService friendService = new FriendService();
            List<Message> messages = friendService.GetMessages(selfId, to, pageNumber, pageSize);
            // 返回结果
            //string messageJson = JsonConvert.SerializeObject(messages, new UnixDateTimeConverter());
            return Json(messages,JsonRequestBehavior.AllowGet);
        }
    }
    
}